import { PublishLaya2Base } from "./PublishLaya2Base";
import { join } from "path";
import rimraf = require("rimraf");
import { IPublishVo, IProjectVo } from "../data/Config";
import { existsSync, readFileSync, writeFileSync } from "fs";
import { cpDir, cpFile } from "../utils/FileUtil";
import { getRoot } from "../data/Config";
let path = require("path");

export class HuaWeiPublish extends PublishLaya2Base {
    get projDir() { return "huaweigame"; }
    get libJs() { return ""; }
    private _isDebug: boolean;
    init(publishVo: IPublishVo, projectInfo: IProjectVo) {
        super.init(publishVo, projectInfo);
        this._isDebug = !this._publishVo.content.chkRelease;
    }

    async createProject() {
        this.log("初始化工具项目目录(第一次初始化比较慢，请耐心等待)");
        let toolPath = path.join(this.mToolPath, 'huawei');
        await this.exec("npm i", { cwd: toolPath, shell: true });
        let toPath = this.mProjPath
        if (existsSync(toPath)) {
            this.doPack();
            return;
        }
        this.log('创建项目目录:' + toPath);

        let tplPath = this.mTempProjPath
        rimraf(toPath, (err2) => {
            if (err2) {
                console.warn(`清理目录${toPath}出错`);
                return;
            }

            cpDir(tplPath, toPath, () => {
                this.log('项目生成完毕 下一步可以开始打包游戏了');
                this.doPack();
            });
        });
    }

    async doPack() {
        await this.buildProject();
        await this._copyIcon();
        this._createMainFast();
        await this._buildRpk();
        this.packOver();
    }

    private async _copyIcon() {
        if (this._publishVo.content && this._publishVo.content.icon) {
            cpFile(this._publishVo.content.icon, path.join(this.mProjPath, "image", path.basename(this._publishVo.content.icon)));
        }
        this.log("复制icon");
    }

    private _createMainFast() {
        // 修改manifest.json文件
        let manifestPath = path.join(this.mProjPath, "manifest.json");
        if (!existsSync(manifestPath)) {
            return;
        }
        let manifestContent = readFileSync(manifestPath, "utf8");
        let manifestJson = JSON.parse(manifestContent.replace(/\s/g, ""));
        manifestJson.package = this._publishVo.content.appId;
        manifestJson.name = this._publishVo.content.name;
        // manifestJson.orientation = config.vivoInfo.orientation;
        manifestJson.config.logLevel = this._isDebug ? "debug" : "off";
        // manifestJson.deviceOrientation = config.vivoInfo.orientation;
        manifestJson.versionName = this._version;
        manifestJson.versionCode = this._publishVo.content.versionCode;
        manifestJson.minPlatformVersion = Number(this._publishVo.content.minSdkVersion || "1075");
        manifestJson.icon = `/image/${path.basename(this._publishVo.content.icon)}`;
        writeFileSync(manifestPath, JSON.stringify(manifestJson, null, 4), "utf8");
        // 修改game.js文件
        // let content = `console.log("启动了");require("./libs/${this.libJs}");\nrequire("./config.js");\nrequire("./src/huawei-adapter.js");\nrequire("./src/laya.hwmini.min.js");\nrequire("./index.js");\nrequire("./src/modify-code-huawei.js")`;
        let content = `require("./config.js");\nrequire("./src/huawei-adapter.js");\nrequire("./src/laya.hwmini.min.js");\nrequire("index.js");`;
        let gameJsPath = path.join(this.mProjPath, "game.js");
        writeFileSync(gameJsPath, content, "utf8");

        // vivo项目，修改index.js
        let filePath = path.join(this.mProjPath, "index.js");
        if (!existsSync(filePath)) {
            return;
        }
        let fileContent = readFileSync(filePath, "utf8");
        fileContent = fileContent.replace(/loadLib(\(['"])/gm, "require$1./");
        writeFileSync(filePath, fileContent, "utf8");
    }

    private async _buildRpk() {
        let privateKey = path.join(this._publishVo.content.cert, "private.pem");
        let publicKey = path.join(this._publishVo.content.cert, "certificate.pem");
        let toolPath = path.join(this.mToolPath, 'huawei/index.js');
        let cmd = `node ${"\""+toolPath+"\""} ${this.mProjPath} ${this.mOutPath + '/dist'} ${this._publishVo.content.name + '_' + this._version} ${privateKey} ${publicKey}`;
        await this.exec(cmd);
      //   await this.exec(`node ${toolPath} ${this.mProjPath} ${this.mOutPath + '/dist'} ${this._publishVo.content.name + '_' + this._version} ${privateKey} ${publicKey}`)
        // let cmd = path.join(this.mTempProjPath, "lib", "bin", `quickgame.cmd`);
        // cmd += " pack";
        // if (!this._isDebug) {
        //     cmd += " release";
        // }
        // await this.exec(cmd, { cwd: this.mProjPath });
    }

    async showPreView() {
        await this.exec(`adb push ${this._publishVo.content.appId}.rpk sdcard/`, { cwd: this.mOutPath, shell: true });
        await this.exec(`adb shell am start -n com.huawei.fastapp.dev/com.huawei.fastapp.app.management.ui.FastAppCenterActivity`, { cwd: this.mProjPath, shell: true });
        this.spawn("adb", ["logcat", "|", "find", '"com.huawei.fastapp.dev"']);
    }

    getEngineVersion() {
        let workSpaceDir = this._publishVo.fromPath;
        let coreLibPath = path.join(workSpaceDir, "libs", "laya.core.js");
        let isHasCoreLib = existsSync(coreLibPath);
        let EngineVersion;
        if (isHasCoreLib) {
            let con = readFileSync(coreLibPath, "utf8");
            let matchList = con.match(/Laya\.version\s*=\s*['"]([0-9\.]+(beta)?.*)['"]/);
            if (!Array.isArray(matchList)) {
                return null;
            }
            EngineVersion = matchList[1];
        }
        return EngineVersion;
    }

    protected mWriteConfig() {
        writeFileSync(join(this.mProjPath, this.getConfigName()), "window.config = " + this.config + ";");
    }
}